package com.cy.server.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.cy.server.dto.EmployeeDto;
import com.cy.server.pojo.*;
import com.cy.server.service.*;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author LiShaoZhuo
 * @since 2021-04-26
 */
@RestController
@RequestMapping("/employee/basic")
public class EmployeeController {

    @Autowired
    IEmployeeService employeeService;
    @Autowired
    IPoliticsStatusService politicsStatusService;
    @Autowired
    IPositionService positionService;
    @Autowired
    IJoblevelService joblevelService;
    @Autowired
    IDepartmentService departmentService;
    @Autowired
    INationService nationService;

    @ApiOperation("员工信息分页")
    @PostMapping("/list")
    public RespBean selectEmployee(@RequestBody EmployeeDto employeeDto){
        PageInfo<Employee> pageInfo = employeeService.selectEmployee(employeeDto);
        return RespBean.success(pageInfo);
    }

    @ApiOperation("查询政治面貌信息")
    @GetMapping("/politicsStatus")
    public List<PoliticsStatus> selectPolitics(){
        return politicsStatusService.list();
    }

    @ApiOperation("查询职位信息")
    @GetMapping("/position")
    public List<Position> selectPosition(){
        return positionService.list();
    }

    @ApiOperation("查询职称信息")
    @GetMapping("/jobLevel")
    public List<Joblevel> selectJobLevel(){
        return joblevelService.list();
    }

    @ApiOperation("查询部门信息")
    @GetMapping("/department")
    public List<Department> selectDepartment(){
        return departmentService.getAllDepartments();
    }

    @ApiOperation("查询民族信息")
    @GetMapping("/nation")
    public List<Nation> selectNation(){
        return nationService.list();
    }

    @ApiOperation("获取最大工号")
    @GetMapping("/maxWorkId")
    public RespBean selectMaxWorkId(){
        return employeeService.selectMaxWorkId();
    }

    @ApiOperation("添加员工")
    @PostMapping("/add")
    public RespBean addEmployee(@RequestBody Employee employee){
        return employeeService.addEmployee(employee);
    }

    @ApiOperation("更新员工")
    @PutMapping("/update")
    public RespBean updateEmployee(@RequestBody Employee employee){
        if (employeeService.updateById(employee)){
            return RespBean.success("更新成功");
        }
        return RespBean.error("更新失败");
    }

    @ApiOperation("删除员工")
    @DeleteMapping("/delete/{id}")
    public RespBean deleteEmployee(@PathVariable Integer id){
        if (employeeService.removeById(id)){
            return RespBean.success("删除成功");
        }
        return RespBean.error("删除失败");
    }

    @ApiOperation("导出数据")
    @GetMapping(value = "/export",produces = "application/octet-stream")
    public void exportEmployee(HttpServletResponse response){
        List<Employee> list = employeeService.getEmployee(null);
        ExportParams exportParams = new ExportParams("员工表","员工表", ExcelType.HSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams,Employee.class, list);
        ServletOutputStream outputStream = null;
        try {
            //流形式
            response.setHeader("content-type", "application/octet-stream");
            //防止中文乱码
            response.setHeader("content-disposition", "attachment;filename="+ URLEncoder.encode("员工表.xls", "UTF-8"));
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (outputStream != null ){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @ApiOperation("导入数据")
    @PostMapping("/import")
    public RespBean importEmployee(MultipartFile file){
        ImportParams importParams = new ImportParams();
        //去掉标题行
        importParams.setTitleRows(1);
        List<Nation> nationList = nationService.list();
        List<PoliticsStatus> politicsStatusList = politicsStatusService.list();
        List<Joblevel> joblevelList = joblevelService.list();
        List<Department> departmentList = departmentService.list();
        List<Position> positionList = positionService.list();
        try {
            List<Employee> list = ExcelImportUtil.importExcel(file.getInputStream(), Employee.class, importParams);
            list.forEach(employee->{
                //民族id
                employee.setNationId(nationList.get(nationList.indexOf(new Nation(employee.getNation().getName()))).getId());
                //政治面貌id
                employee.setPoliticId(politicsStatusList.get(politicsStatusList.indexOf(new PoliticsStatus(employee.getPoliticsStatus().getName()))).getId());
                //职称id
                employee.setJobLevelId(joblevelList.get(joblevelList.indexOf(new Joblevel(employee.getJoblevel().getName()))).getId());
                //部门id
                employee.setDepartmentId(departmentList.get(departmentList.indexOf(new Department(employee.getDepartment().getName()))).getId());
                //职位id
                employee.setPosId(positionList.get(positionList.indexOf(new Position(employee.getPosition().getName()))).getId());
            });
            if (employeeService.saveBatch(list)){
                return RespBean.success("导入成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return RespBean.error("导入失败");
    }
}
